﻿using EOM.TSHotelManagement.Common.Contract;
using EOM.TSHotelManagement.Common.Core;
using EOM.TSHotelManagement.Common.Util;
using EOM.TSHotelManagement.EntityFramework;
using jvncorelib.EntityLib;
using SqlSugar;

namespace EOM.TSHotelManagement.Application
{
    /// <summary>
    /// 工具接口实现类
    /// </summary>
    public class UtilService : IUtilService
    {
        /// <summary>
        /// 卡片代码
        /// </summary>
        private readonly GenericRepository<CardCode> cardCodesRepository;

        /// <summary>
        /// 操作日志
        /// </summary>
        private readonly GenericRepository<OperationLog> operationLogRepository;

        /// <summary>
        /// 请求日志
        /// </summary>
        private readonly GenericRepository<RequestLog> requestLogRepository;

        public UtilService(GenericRepository<CardCode> cardCodesRepository, GenericRepository<OperationLog> operationLogRepository, GenericRepository<RequestLog> requestLogRepository)
        {
            this.cardCodesRepository = cardCodesRepository;
            this.operationLogRepository = operationLogRepository;
            this.requestLogRepository = requestLogRepository;
        }

        /// <summary>
        /// 查询身份证号码
        /// </summary>
        /// <param name="readCardCodeInputDto"></param>
        /// <returns></returns>
        public SingleOutputDto<ReadCardCodeOutputDto> SelectCardCode(ReadCardCodeInputDto readCardCodeInputDto)
        {
            if (!readCardCodeInputDto.IdentityCardNumber.IsNullOrEmpty())
            {
                var cardid = readCardCodeInputDto.IdentityCardNumber.Substring(0, 6).ToString();
                var cardcodes = cardCodesRepository.GetFirst(a => a.AreaCode == cardid);
                var source = EntityMapper.Map<CardCode, ReadCardCodeOutputDto>(cardcodes);
                return new SingleOutputDto<ReadCardCodeOutputDto>() { Data = source };
            }
            return new SingleOutputDto<ReadCardCodeOutputDto>();
        }

        /// <summary>
        /// 添加操作日志
        /// </summary>
        /// <param name="opr"></param>
        /// <returns></returns>
        public BaseResponse AddLog(CreateOperationLogInputDto opr)
        {
            try
            {
                var log = EntityMapper.Map<CreateOperationLogInputDto, OperationLog>(opr);
                var result = operationLogRepository.Insert(log);
                if (!result)
                {
                    return new BaseResponse { Message = LocalizationHelper.GetLocalizedString("Add Log Failed", "添加日志失败"), Code = BusinessStatusCode.InternalServerError };
                }
            }
            catch (Exception ex)
            {
                return new BaseResponse { Message = LocalizationHelper.GetLocalizedString(ex.Message, ex.Message), Code = BusinessStatusCode.InternalServerError };
            }
            return new BaseResponse();
        }

        /// <summary>
        /// 查询所有操作日志
        /// </summary>
        /// <returns></returns>
        public ListOutputDto<ReadOperationLogOutputDto> SelectOperationlogAll(ReadOperationLogInputDto readOperationLogInputDto)
        {
            List<OperationLog> operationLogs = new List<OperationLog>();

            var where = Expressionable.Create<OperationLog>();

            if (!readOperationLogInputDto.IsDelete.IsNullOrEmpty())
            {
                where = where.And(a => a.IsDelete == readOperationLogInputDto.IsDelete);
            }
            if (!readOperationLogInputDto.LogLevel.IsNullOrEmpty())
            {
                if (readOperationLogInputDto.LogLevel.HasValue)
                {
                    where = where.And(a => a.LogLevel == (LogLevel)readOperationLogInputDto.LogLevel.Value);
                }
            }

            var count = 0;
            if (readOperationLogInputDto.Page != 0 && readOperationLogInputDto.PageSize != 0)
            {
                operationLogs = operationLogRepository.AsQueryable().Where(where.ToExpression()).OrderByDescending(a => a.OperationTime).ToPageList(readOperationLogInputDto.Page, readOperationLogInputDto.PageSize, ref count);
            }
            else
            {
                operationLogs = operationLogRepository.AsQueryable().Where(where.ToExpression()).OrderByDescending(a => a.OperationTime).ToList();
                count = operationLogs.Count;
            }

            operationLogs.ForEach(source =>
            {
                source.LogLevelName = source.LogLevel == LogLevel.Normal ? LocalizationHelper.GetLocalizedString("INFO", "常规操作") : source.LogLevel == LogLevel.Warning ? LocalizationHelper.GetLocalizedString("WARNING", "敏感操作") : LocalizationHelper.GetLocalizedString("ERROR", "严重操作");
            });

            var result = EntityMapper.MapList<OperationLog, ReadOperationLogOutputDto>(operationLogs);

            return new ListOutputDto<ReadOperationLogOutputDto>
            {
                Data = new PagedData<ReadOperationLogOutputDto>
                {
                    Items = result,
                    TotalCount = count
                }
            };
        }

        /// <summary>
        /// 查询所有请求日志
        /// </summary>
        /// <param name="readRequestLogInputDto"></param>
        /// <returns></returns>
        public ListOutputDto<ReadRequestLogOutputDto> SelectRequestlogAll(ReadRequestLogInputDto readRequestLogInputDto)
        {
            List<RequestLog> requestLogs = new List<RequestLog>();

            var where = Expressionable.Create<RequestLog>();

            if (!readRequestLogInputDto.IsDelete.IsNullOrEmpty())
            {
                where = where.And(a => a.IsDelete == readRequestLogInputDto.IsDelete);
            }

            var count = 0;
            if (readRequestLogInputDto.Page != 0 && readRequestLogInputDto.PageSize != 0)
            {
                requestLogs = requestLogRepository.AsQueryable().Where(where.ToExpression()).OrderByDescending(a => a.RequestTime).ToPageList(readRequestLogInputDto.Page, readRequestLogInputDto.PageSize, ref count);
            }
            else
            {
                requestLogs = requestLogRepository.AsQueryable().Where(where.ToExpression()).OrderByDescending(a => a.RequestTime).ToList();
                count = requestLogs.Count;
            }

            var result = EntityMapper.MapList<RequestLog, ReadRequestLogOutputDto>(requestLogs);

            return new ListOutputDto<ReadRequestLogOutputDto>
            {
                Data = new PagedData<ReadRequestLogOutputDto>
                {
                    Items = result,
                    TotalCount = count
                }
            };
        }

        /// <summary>
        /// 删除指定时间范围的操作日志
        /// </summary>
        /// <returns></returns>
        public BaseResponse DeleteOperationlogByRange(ReadOperationLogInputDto readOperationLogInputDto)
        {
            try
            {
                var where = Expressionable.Create<OperationLog>();

                if (readOperationLogInputDto.StartTime.HasValue && readOperationLogInputDto.EndTime.HasValue)
                {
                    where = where.And(a => a.OperationTime >= readOperationLogInputDto.StartTime && a.OperationTime <= readOperationLogInputDto.EndTime);
                }

                var logsToDelete = operationLogRepository.AsQueryable().Where(where.ToExpression()).ToList();

                if (logsToDelete.Any())
                {
                    operationLogRepository.Delete(logsToDelete);
                }
            }
            catch (Exception ex)
            {
                return new BaseResponse { Message = LocalizationHelper.GetLocalizedString(ex.Message, ex.Message), Code = BusinessStatusCode.InternalServerError };
            }
            return new BaseResponse { Message = "操作日志删除成功", Code = BusinessStatusCode.Success };
        }

        /// <summary>
        /// 删除操作日志
        /// </summary>
        /// <returns></returns>
        public BaseResponse DeleteOperationlog(DeleteOperationLogInputDto deleteOperationLogInputDto)
        {
            var result = operationLogRepository.Delete(a => a.OperationId == deleteOperationLogInputDto.OperationId);

            if (result)
            {
                return new BaseResponse(BusinessStatusCode.Success, LocalizationHelper.GetLocalizedString("Delete Operation Log Success", "操作日志删除成功"));
            }
            else
            {
                return new BaseResponse(BusinessStatusCode.InternalServerError, LocalizationHelper.GetLocalizedString("Delete Operation Log Failed", "操作日志删除失败"));
            }
        }
    }
}
